package com.wysql.ascost.service.info;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wysql.ascost.common.base.BaseService;
import com.wysql.ascost.common.exception.demo.ExcelImportZdyException;
import com.wysql.ascost.common.exception.demo.FileNameException;
import com.wysql.ascost.common.support.ConvertUtil;
import com.wysql.ascost.mapper.info.InfoContractstoreDtlMapper;
import com.wysql.ascost.mapper.info.InfoContractstoreMapper;
import com.wysql.ascost.mapper.info.InfoFileMapper;
import com.wysql.ascost.model.custom.Tablepar;
import com.wysql.ascost.model.info.*;
import com.wysql.ascost.util.SnowflakeIdWorker;
import com.wysql.ascost.util.StringUtils;
import com.wysql.ascost.util.TestForExcel2PDF;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 协议库存信息查询--主表 InfoContractstoreService
 *
 * @author wysqlauto_自动生成
 * @Title: InfoContractstoreService.java 
 * @Package com.wysql.ascost.service 
 * @email ${email}
 * @date 2025-03-10 15:10:54  
 **/
@Service
public class InfoContractstoreService implements BaseService<InfoContractstore, InfoContractstoreExample> {
    static String singleSlash = "/";
    @Value("${file.uploadUrl}")
    private String uploadPath;
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;

    @Autowired
    private InfoContractstoreMapper infoContractstoreMapper;
    @Autowired
    private InfoContractstoreDtlMapper infoContractstoreDtlMapper;
    @Autowired
    private InfoFileMapper infoFileMapper;

    /**
     * 分页查询
     *
     * @param
     * @param
     * @return
     */
    public PageInfo<InfoContractstore> list(Tablepar tablepar, InfoContractstore infoContractstore) {
        InfoContractstoreExample testExample = new InfoContractstoreExample();
        //搜索
        if (StrUtil.isNotEmpty(tablepar.getSearchText())) {//小窗体
            testExample.createCriteria().andLikeQuery2(tablepar.getSearchText());
        } else {//大搜索
            testExample.createCriteria().andLikeQuery(infoContractstore);
        }
        //表格排序
        if(StrUtil.isNotEmpty(tablepar.getOrderByColumn())) {
        	testExample.setOrderByClause(StringUtils.toUnderScoreCase(tablepar.getOrderByColumn()) +" "+tablepar.getIsAsc());
        }else{
        	testExample.setOrderByClause("creattime DESC");
        }
        PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
        List<InfoContractstore> list = infoContractstoreMapper.selectByExample(testExample);
        PageInfo<InfoContractstore> pageInfo = new PageInfo<InfoContractstore>(list);
        return pageInfo;
    }

    @Override
    public int deleteByPrimaryKey(String ids) {

        List<String> lista = ConvertUtil.toListStrArray(ids);
        InfoContractstoreExample example = new InfoContractstoreExample();
        example.createCriteria().andIdIn(lista);
        return infoContractstoreMapper.deleteByExample(example);


    }


    @Override
    public InfoContractstore selectByPrimaryKey(String id) {

        return infoContractstoreMapper.selectByPrimaryKey(id);

    }


    @Override
    public int updateByPrimaryKeySelective(InfoContractstore record) {
        return infoContractstoreMapper.updateByPrimaryKeySelective(record);
    }


    /**
     * 添加
     */
    @Override
    public int insertSelective(InfoContractstore record) {

        //添加雪花主键id
        record.setId(SnowflakeIdWorker.getUUID());


        return infoContractstoreMapper.insertSelective(record);
    }


    @Override
    public int updateByExampleSelective(InfoContractstore record, InfoContractstoreExample example) {

        return infoContractstoreMapper.updateByExampleSelective(record, example);
    }


    @Override
    public int updateByExample(InfoContractstore record, InfoContractstoreExample example) {

        return infoContractstoreMapper.updateByExample(record, example);
    }

    @Override
    public List<InfoContractstore> selectByExample(InfoContractstoreExample example) {

        return infoContractstoreMapper.selectByExample(example);
    }


    @Override
    public long countByExample(InfoContractstoreExample example) {

        return infoContractstoreMapper.countByExample(example);
    }


    @Override
    public int deleteByExample(InfoContractstoreExample example) {

        return infoContractstoreMapper.deleteByExample(example);
    }


    @Transactional
    public Map<String, Object> uploadFile(MultipartFile file) throws Exception {
        System.err.println("++++++++++++++++++" + file.getOriginalFilename());
        Map<String, Object> map = new HashMap<>();
        // 0、初始化、定义执行结果变量
        String returnStr = "";
        int successNum = 0;// 成功条数
        int failNum = 0;// 失败条数

        String mainUUid = SnowflakeIdWorker.getUUID();//提前生成，用于明细表插入

        String realname = file.getOriginalFilename();//导入原始文件名称
        //特殊符号正则处理
        String filename = this.repairName(realname);//导入原始文件名称经过特殊符号处理后名称

        // 1、导入数据获取
        List<InfoContractstoreDtl> list = importExcelList(file.getInputStream(),filename,mainUUid);

        if (list!=null && list.size()>0){
            for (InfoContractstoreDtl infoContractstoreDtl : list) {
                if (infoContractstoreDtlMapper.insert(infoContractstoreDtl) > 0) {
                    successNum = successNum + 1;
                } else {
                    failNum = failNum + 1;
                    returnStr = returnStr + "在" + infoContractstoreDtl.getId() + "行发生错误[数据库执行失败]<br>";
                }
            }
        }

        //3、 插入日志表，返回导入结果
        InfoContractstore infoContractstore = new InfoContractstore();
        infoContractstore.setId(mainUUid);
        infoContractstore.setFilename(realname);
        infoContractstore.setCreattime(new Date());
        infoContractstoreMapper.insertSelective(infoContractstore);

        //上传文件至服务器
        String pathString = null;
        String uuid = UUID.randomUUID().toString();
        Calendar calendar = Calendar.getInstance();
        String tm = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1);
        Long size = file.getSize();
        //获取上传的文件名称
        //chrome会获取到该文件的直接文件名称，IE/Edge会获取到文件上传时完整路径/文件名
        //Check for Unix-style path
        int unixSep = filename.lastIndexOf('/');
        //Check for Windows-style path
        int winSep = filename.lastIndexOf('\\');
        //cut off at latest possible point
        int pos = (winSep > unixSep ? winSep : unixSep);
        if (pos != -1) {
            filename = filename.substring(pos + 1);
        }
        String pdffilename = filename.substring(0, filename.lastIndexOf("."));
        pathString = uploadPath + tm + singleSlash + uuid + singleSlash + filename;
        String pdfpathString = uploadPath + tm + singleSlash + uuid + singleSlash + pdffilename + ".pdf";
        File files = new File(pathString);
        if (!files.getParentFile().exists()) {
            files.getParentFile().mkdirs();
        }
        file.transferTo(files);
        map.put("code", 0);
        map.put("fileUrl", staticAccessPath + tm + singleSlash + uuid + singleSlash + filename);
        map.put("fileName", filename);
        map.put("localPath", pathString);
        map.put("size", size);

        //业务文件表中增加excel文件记录
        createFileExcel(pathString, map, realname, mainUUid);
//        //Excel转换为PDF上传至服务器文件夹
//        TestForExcel2PDF.excel2pdf(pathString, pdfpathString);
//        //业务文件表中增加pdf文件记录
//        createFilePdf(pdfpathString, map, realname, infoProjectbudget);

        map.put("code", 0);
        map.put("msg", "导入成功[" + successNum + "]条数据");
        return map;
    }

    /**
     * @Title: repairName
     * @Author: ShengQL
     * @Date: 2024/12/17 10:19
     * @Params: [realname]
     * @Return: String
     * @Description: 对于文件名称中特殊符号的处理
     */
    private String repairName(String realname) {
        //1、目前仅处理#号
        realname = realname.replaceAll("#", "号");
        return realname;
    }

    public List<InfoContractstoreDtl> importExcelList(InputStream inputStream,String filename,String mainid) throws IOException {

        // 定义一个List，用来存放excel表中的值
        List<InfoContractstoreDtl> resultList = new ArrayList<InfoContractstoreDtl>();

        // 1、传入获取的工作流, workbook,是一个工作簿，使用excel能操作的这边它都可以操作，这一个操作，相当于是把Excel放到Java中使用
        Workbook wb = null;
        String extString = filename.substring(filename.lastIndexOf("."));
        if (".xls".equals(extString)) {
            wb = new HSSFWorkbook(inputStream);
        } else if (".xlsx".equals(extString)) {
            wb = new XSSFWorkbook(inputStream);
        }
        // 2、获取工作簿中的表,对表中的设置，通过下标去拿第一张表
        Sheet sheet = wb.getSheetAt(0);
        // 3、获取表格总的行数
        int rowNumber = sheet.getPhysicalNumberOfRows();

        // 从第二行开始读取每一行数据，我们设置的模板表头是在第一、第二行，下标从0开始。
        for (int rowNum = 1; rowNum < rowNumber; rowNum++) {
            InfoContractstoreDtl infoContractstoreDtl = new InfoContractstoreDtl();
            // 获取工作表中第二行的数据
            Row rowData = sheet.getRow(rowNum);
            if (rowData != null) {
                infoContractstoreDtl.setId(SnowflakeIdWorker.getUUID());
                infoContractstoreDtl.setMainid(mainid);
                infoContractstoreDtl.setCreattime(new Date());
                infoContractstoreDtl.setMemo(importExcel(rowData.getCell(1), wb));
                Cell cell = rowData.getCell(2);
                cell.setCellType(CellType.STRING);
                infoContractstoreDtl.setMatnum(cell.getRichStringCellValue().getString());
                infoContractstoreDtl.setMatname(importExcel(rowData.getCell(3), wb));
                infoContractstoreDtl.setMatunit(importExcel(rowData.getCell(4), wb));
                infoContractstoreDtl.setTechid(importExcel(rowData.getCell(5), wb));
                infoContractstoreDtl.setDtlmemo(importExcel(rowData.getCell(6), wb));
                infoContractstoreDtl.setPrice(new BigDecimal(importExcel(rowData.getCell(7), wb)));
                infoContractstoreDtl.setPartmemo(importExcel(rowData.getCell(8), wb));
                infoContractstoreDtl.setMattype1(importExcel(rowData.getCell(9), wb));
                infoContractstoreDtl.setMattype2(importExcel(rowData.getCell(10), wb));
                infoContractstoreDtl.setMattype3(importExcel(rowData.getCell(11), wb));
                infoContractstoreDtl.setTargetnum(importExcel(rowData.getCell(12), wb));
                infoContractstoreDtl.setBatchvalue(importExcel(rowData.getCell(13), wb));
                infoContractstoreDtl.setExevalue(importExcel(rowData.getCell(14), wb));
                cell = rowData.getCell(15);
                cell.setCellType(CellType.STRING);
                infoContractstoreDtl.setErpnum(cell.getRichStringCellValue().getString());
            }

            resultList.add(infoContractstoreDtl);
        }
        // 循环结束后，把从excel表读取的对象放到excelList中。
        // 关闭流
        inputStream.close();

        // 返回list结果
        return resultList;
    }

    public static String importExcel(Cell cell, Workbook wb) throws IOException {
        String value = "";
        //后面使用它来执行计算公式
//        FormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook) wb);
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                value = String.valueOf(cell.getNumericCellValue()).substring(0, String.valueOf(cell.getNumericCellValue()).length() - 2);
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            case Cell.CELL_TYPE_FORMULA:
////             value = String.valueOf(cell.getNumericCellValue());
//                String cellFormula = cell.getCellFormula();
//                CellValue evaluate = formulaEvaluator.evaluate(cell);
//                value = Objects.equals("#N/A", evaluate.formatAsString()) ? "" : evaluate.formatAsString();
//                break;
            default:
                value = cell.toString();
                break;
        }
        return value;
    }

    private void createFileExcel(String pathString, Map<String, Object> map, String realname,String recordid) {
        //新增业务文件台账记录，记录文件地址等信息
        //上传成功后记录附件信息至业务附件表
        InfoFile infoFile = new InfoFile();
        infoFile.setId(UUID.randomUUID().toString());
        infoFile.setLocationPath(pathString);
        infoFile.setFileUrl(map.get("fileUrl").toString());
        infoFile.setFileSize(Integer.valueOf(map.get("size").toString()));
        //处理后的文件名
        infoFile.setFileName(map.get("fileName").toString());
        infoFile.setRealName(realname);
        infoFile.setFkSubject("1");
        infoFile.setFkRecord(recordid);
        infoFile.setSuffix(realname.substring(realname.lastIndexOf(".")));
        infoFile.setCreateDate(new Date());
        infoFile.setFkTaskId("");
        infoFileMapper.insertSelective(infoFile);
    }

}
